package com.junjiao.util.java;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * properties文件操作工具类
 * 
 * @author jiaojun
 *         <p>
 *         email:junjiao.j@gmail.com
 *         </p>
 * @version v0.0.2
 * @date 2012-5-17
 */
public class PropertyUtil {

	Properties pds;

	/**
	 * 根据properties配置文件的key获取对应的value，支持porperties、xml两种文件格式
	 * 
	 * @param file
	 *            一般给文件放于和class同级的目录中，只传文件名
	 * @param key
	 *            key
	 * @return value value
	 */
	public static String getPropertiesByKey(String file, String key) {
		String str = "";
		Properties properties = new Properties();
		InputStream inStream = null;
		try {
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			inStream = loader.getResourceAsStream(file);
			if (file.endsWith(".properties")) {
				properties.load(inStream);
			} else if (file.endsWith(".xml")) {
				properties.loadFromXML(inStream);
			}
			str = properties.getProperty(key);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return str;
	}

	/**
	 * 初始化Properties对象
	 * 
	 * @param propertiesPath
	 *            文件路径
	 */
	public PropertyUtil(String propertiesPath) {
		InputStream inStream = null;
		try {
			this.pds = new Properties();
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			inStream = loader.getResourceAsStream(propertiesPath);
			this.pds.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据properties配置文件的key获取对应的value
	 * 
	 * @param key
	 *            key
	 * @return
	 */
	public String get(String key) {
		return this.pds.getProperty(key);
	}

	public static Properties getProperties(String propertiesPath) {
		Properties pds = new Properties();
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		InputStream inStream = loader.getResourceAsStream(propertiesPath);
		try {
			pds.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return pds;
	}
}
